package com.gitee.ixtf.vertx.rabbitmq.kotlinx

import com.gitee.ixtf.core.kotlinx.readJson
import com.gitee.ixtf.vertx.kotlinx.readJson
import com.gitee.ixtf.vertx.kotlinx.unGzip
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.rabbitmq.RabbitMQMessage
import reactor.rabbitmq.AcknowledgableDelivery

fun RabbitMQMessage.routingKey(): String = envelope().routingKey

fun RabbitMQMessage.jsonObject(): JsonObject = body().toJsonObject()

fun RabbitMQMessage.jsonArray(): JsonArray = body().toJsonArray()

inline fun <reified T> RabbitMQMessage.readJson(): T = body().readJson()

inline fun <reified T> RabbitMQMessage.readJsonByGzip(): T = body().unGzip().readJson()

fun RabbitMQMessage.dlx() =
    (properties().headers["x-death"] as List<*>)
        .asSequence()
        .map { it as Map<*, *> }
        .flatMap { xDeath ->
          val exchange = "${xDeath["exchange"]}"
          (xDeath["routing-keys"] as List<*>).map { exchange to "$it" }
        }

fun AcknowledgableDelivery.dlx() =
    (properties.headers["x-death"] as List<*>)
        .asSequence()
        .map { it as Map<*, *> }
        .flatMap { xDeath ->
          val exchange = "${xDeath["exchange"]}"
          (xDeath["routing-keys"] as List<*>).map { exchange to "$it" }
        }
